﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_OrderRequest_SaleOrderRequest : System.Web.UI.UserControl
{
    DBDataContext db = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.txtCustomerCode.Focus();
            loadDataForm();
            LoadFormForCustomerTab();
           // Session["Cus"] = null;

            if (Session["SaleOrderRequestID"] != null && !String.IsNullOrEmpty(Session["SaleOrderRequestID"].ToString()))//tao don hang tu don dat hang
            {
                int ID = Convert.ToInt32(Session["SaleOrderRequestID"]);
                ViewState["SaleOrderRequestID"] = ID;
                Session["SaleOrderRequestID"] = null;
                Session.Remove("SaleOrderRequestID");
                loadDataViewFromSOR(ID);
            }
            else
            {
                dtpReceiptDate.SelectedDate = DateTime.Now.Date;
                dtpReceiptDate.MinDate = DateTime.Now;
            }

            loadDataGrid();
        }
    }

    private void loadDataViewFromSOR(int SaleOrderRequestID)
    {
        try
        {
            var sor = (from s in db.SaleOrderRequests
                       join cd in db.CodeDetails on s.Status.ToString() equals cd.CDCode
                       join c in db.Customers on s.CustomerID equals c.ID
                       where s.ID == SaleOrderRequestID
                       && cd.CMCode == "SaleOderRequestStatus"
                       select new
                       {
                           s.SaleOrderRequestCode,
                           s.Total,
                           s.TotalWeight,
                           s.PhoneNumberReceipt,
                           s.DateTimeReceipt,
                           s.PersonReceipt,
                           s.AddressReceipt,
                           c.CustomerCode,
                           c.CustomerName,
                           s.DiscountAmount,
                           s.CreatedDateTime,
                           s.Amount,
                           s.ShopID,
                           Status = cd.CDName,
                           s.TotalWeightPromotion,
                           s.TotalAmountPoint
                       }).FirstOrDefault();

            txtSaleOrderStatus.Text = sor.Status;
            cboShop.SelectedValue = sor.ShopID.ToString();
            txtSaleOrderCode.Text = sor.SaleOrderRequestCode;
            txtCustomerCode.Text = sor.CustomerCode;
            txtCustomerName.Text = sor.CustomerName;
            txtReceiptAdress.Text = sor.AddressReceipt;
            txtReceiptPerson.Text = sor.PersonReceipt;
            txtReceiptPhoneNumer.Text = sor.PhoneNumberReceipt;
            dtpReceiptDate.SelectedDate = sor.DateTimeReceipt;

            string urlImage = Utils.getUrlImage();
            DataTable dtPromotion = new DataTable();
            //Load KM da chon
            var listPromotion = (from sp in db.SaleOrderRequestPromotions
                                 join p in db.Products on sp.ProductID equals p.ID
                                 where p.ProductType == "P" && p.Status == 'A'
                                 && sp.SaleOrderRequestID == SaleOrderRequestID
                                 select new
                                 {
                                     Image =urlImage+ p.ImagePath,
                                     sp.ProductID,
                                     sp.PromotionID,
                                     sp.PromotionDetailID,
                                     sp.Weight,
                                     p.ProductName,
                                     PromotionQuantity = sp.PromotionRemainQty,
                                     PromotionQuantitySelect = sp.QuantitySelect
                                 }).ToList();


            dtPromotion = listPromotion.ToDataTable();
            bindingPromotion(dtPromotion);
            ViewState["dtPromotion"] = dtPromotion;

            //chi tiet sp
            var listProduct = (from list in db.SaleOrderRequestDetails
                               join p in db.Products on list.ProductID equals p.ID
                               where list.SaleOrderRequestID == SaleOrderRequestID
                               && p.Status == 'A'
                               select new
                               {
                                   list.ProductID,
                                   p.ProductName,
                                   ProductCode = p.ProductCode,
                                   list.Price,
                                   list.Weight,
                                   Total = list.Price * list.Weight,
                                   p.IsPromotion,
                                   list.IsPoint
                               }).ToList();

            DataTable dt = listProduct.ToDataTable();
            ViewState["CurrentTable"] = dt;
            // load du lieu tong
            /*
            sumWeightSO.InnerText = sor.TotalWeight.ToString();
            sumWeight.InnerText = sor.TotalWeightPromotion.ToString();
            */
            DivDiscountAmount.InnerText = sor.DiscountAmount.ToString();
            DivAmount.InnerText=sor.Amount.ToString();
            DivSumPayment.InnerText=sor.Total.ToString();
            sumWeight.InnerText=sor.TotalWeightPromotion.ToString();
            sumWeightSO.InnerText=sor.TotalWeight.ToString();
            DivAmountAccumulate.InnerText =sor.TotalAmountPoint.ToString();
            CalsumHelp(DecimalOrNull(sor.Amount), 0, double.Parse(sor.DiscountAmount.ToString()));

            //CalcDiscount(DecimalOrNull(sor.Amount), sor.CreatedDateTime);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-loadDataViewFromSOR");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void loadDataGrid()
    {
        try
        {
            DataTable dt = createDataTable();
            if (dt.Rows.Count > 2)
            {
                gvData.Height = 120;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
            }
            
            ViewState["CurrentTable"] = dt;
            gvData.DataSource = dt;
            gvData.DataBind();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-loadDataGrid");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void loadDataForm()
    {
        try
        {
            
            Utils.LoadCodeDetail(cboIsReceiptBill, "ReceiptBill", 0);
            cboIsReceiptBill.SelectedIndex = 1;

           // Utils.loadProductToCombo(cboProduct);
            Utils.loadProductToComboSearch(cboProduct,0,"R");
            // string EmployeeCode = Session["EmployeeCode"] == null ? "" : Session["EmployeeCode"].ToString();
            // string EmplyeeName = Session["EmplyeeName"] == null ? "" : Session["EmplyeeName"].ToString();

            //txtEmployeeBillCode.Text = EmployeeCode;
            //txtEmployeeBillName.Text = EmplyeeName;
            txtEmployeeBillName.Text = Session["UserName"].ToString();
            this.cboVAT.Visible = false;

            //Load tinh thanh
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
            //load Shop
            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopByProvinceToCombo(cboShop, isShopAll, ProvinceID, ShopID, "");
            //Utils.loadShopToCombo(cboShop, 1, 0,"");
            gvPromotion.DataSource = new DataTable();
            gvPromotion.DataBind();
            gv.DataSource = new DataTable();
            gv.DataBind();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequestRequest-loadDataForm");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private DataTable createDataTable(bool isFirst = true)
    {
        DataTable dt = new DataTable();
        if (ViewState["CurrentTable"] == null)
        {
            dt.Columns.Add("ProductID");
            dt.Columns.Add("ProductCode");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("Price");
            dt.Columns.Add("IsPromotion");
            dt.Columns.Add("IsPoint");
            dt.Columns.Add("Weight");
            dt.Columns.Add("Total");
        }
        else
        {
            dt = (DataTable)ViewState["CurrentTable"];
        }
        return dt;
    }
    private SaleOrderRequest createSaleOrderRequestObj()
    {

        SaleOrderRequest saleOrder = new SaleOrderRequest();
        try
        {
            string saleOrderCode = this.txtSaleOrderCode.Text;
            if (saleOrderCode == "")
            {
                //Lay ma sau cung
                int lenZero = 10;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var CodeMax = db.SaleOrderRequests.Max(d => d.OrderNumber);
                int MaxOrderNumber = (CodeMax == null ? 0 : Convert.ToInt32(CodeMax)) + 1;
                String LastCode = ("0000000000" + MaxOrderNumber).ToString();
                String Code = "DD" + LastCode.Substring(LastCode.Length - lenZero);
                saleOrder.OrderNumber = MaxOrderNumber;
                saleOrder.SaleOrderRequestCode = Code;
                saleOrder.Status = 'N';
            }
            else
            {
                saleOrder = db.SaleOrderRequests.FirstOrDefault<SaleOrderRequest>(so => so.SaleOrderRequestCode == saleOrderCode);
            }
            var CustomerID = (from c in db.Customers where c.CustomerCode == this.txtCustomerCode.Text.Trim() select c.ID).FirstOrDefault();
            //End
           
            saleOrder.CustomerID = CustomerID;
            saleOrder.SaleOderType = "P";
            saleOrder.DiscountAmount = double.Parse(DivDiscountAmount.InnerText);
            saleOrder.Amount = double.Parse(DivAmount.InnerText);
            saleOrder.Total = double.Parse(DivSumPayment.InnerText);
            saleOrder.TotalWeightPromotion = Convert.ToInt32(sumWeight.InnerText);
            saleOrder.TotalWeight = Convert.ToInt32(sumWeightSO.InnerText);
            saleOrder.TotalAmountPoint = Convert.ToInt32(DivAmountAccumulate.InnerText);

            saleOrder.ShopID = IntOrNull(cboShop.SelectedValue);
            //thong tin giao hang
            saleOrder.PersonReceipt = txtReceiptPerson.Text.Trim();
            saleOrder.PhoneNumberReceipt = txtReceiptPhoneNumer.Text.Trim();
            saleOrder.AddressReceipt = txtReceiptAdress.Text.Trim();
            saleOrder.DateTimeReceipt = dtpReceiptDate.SelectedDate;

            saleOrder.CreatedBy = Session["UserName"].ToString(); ;
            saleOrder.LastUpdatedBy = Session["UserName"].ToString();
            saleOrder.CreatedDateTime = DateTime.Now;
            saleOrder.LastUpdatedDateTime = DateTime.Now;
           
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequestRequest-createSaleOrderRequestObj");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return saleOrder;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        using (var transation = new System.Transactions.TransactionScope())
        {
            try
            {
                if (txtCustomerCode.Text == "")
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Khách hàng này không tồn tại. Vui tạo mới khách hàng ơ tab 'Thông tin khách hàng'");
                    RadPageView4.Enabled = true;
                    TabStrip1.SelectedIndex = 1;
                    RadPageView4.Selected = true;

                    return;
                }

                if (gvData.Items.Count > 0)
                {

                    SaleOrderRequest saleOrder = createSaleOrderRequestObj();
                    //string saleOrderCode = this.txtSaleOrderCode.Text;
                    string saleOrderCodeStatus = this.txtSaleOrderStatus.Text;
                    if (saleOrderCodeStatus == "")//Tao moi
                    {
                        db.Insert<SaleOrderRequest>(saleOrder);
                        db.SubmitChanges();
                    }
                    else // Cap nhat
                    {
                        saleOrder.LastUpdatedBy = Session["UserName"].ToString();
                        saleOrder.LastUpdatedDateTime = DateTime.Now;
                        // saleOrder.ID = int.Parse (Session["SaleOrderRequestID"].ToString());
                        db.Update<SaleOrderRequest>(saleOrder);
                        DeletePromotion(saleOrder.ID);
                        DeleteDetail(saleOrder.ID);
                    }


                    //chi tiet sp
                    List<SaleOrderRequestDetail> listDetail = new List<SaleOrderRequestDetail>();
                    foreach (GridDataItem it in gvData.Items)
                    {
                        SaleOrderRequestDetail soDetail = new SaleOrderRequestDetail();

                        soDetail.SaleOrderRequestID = saleOrder.ID;
                        soDetail.ProductID = int.Parse(it["ProductID"].Text);
                        soDetail.IsPoint = Convert.ToByte(it["IsPoint"].Text);
                        soDetail.Price = double.Parse(it["Price"].Text);

                        double weight = double.Parse(it["Weight"].Text.Replace(",", ""));
                        soDetail.Weight = weight;
                        soDetail.Amount = double.Parse(it["Price"].Text) * weight;
                        soDetail.CreatedBy = Session["UserName"].ToString();
                        soDetail.LastUpdatedBy = Session["UserName"].ToString();
                        soDetail.CreatedDateTime = DateTime.Now;
                        soDetail.LastUpdatedDateTime = DateTime.Now;
                        soDetail.Status = 'N';

                        listDetail.Add(soDetail);
                    }
                    db.Insert<SaleOrderRequestDetail>(listDetail);
                    //Insert KM 
                    InsertPromotion(saleOrder.ID);

                    db.SubmitChanges();
                    transation.Complete();
                    this.txtSaleOrderCode.Text = saleOrder.SaleOrderRequestCode;
                    this.txtSaleOrderCode.ReadOnly = true;
                    this.txtCustomerCode.ReadOnly = true;
                    this.txtCustomerName.ReadOnly = true;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công");
                    this.txtSaleOrderStatus.Text = "Tạo mới";
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Danh sách sản phẩm không được trống");
                }
            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("SaleOrderRequest-btnSave_Click");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
                return;
            }
        }
    }
    private void DeletePromotion(int? saleOrderID)
    {
        try
        {
            List<SaleOrderRequestPromotion> saleOrderPromotion = (from sd in db.SaleOrderRequestPromotions where sd.SaleOrderRequestID == saleOrderID select sd).ToList<SaleOrderRequestPromotion>();
            db.Delete<SaleOrderRequestPromotion>(saleOrderPromotion);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-DeletePromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void InsertPromotion(int saleOrderID)
    {
        try
        {
            List<SaleOrderRequestPromotion> listPro = new List<SaleOrderRequestPromotion>();
            foreach (GridDataItem it in gvPromotion.Items)
            {
                SaleOrderRequestPromotion saleOrderPromotion = new SaleOrderRequestPromotion();

                int ProductID = int.Parse(it["ProductID"].Text);
                int PromotionDetailID = int.Parse(it["PromotionDetailID"].Text);
                int PromotionID = int.Parse(it["PromotionDetailID"].Text);
                int PromotionRemainQty = int.Parse(it["PromotionQuantity"].Text);
                int Weight = int.Parse(it["Weight"].Text);
                RadNumericTextBox QuantitySelect = (RadNumericTextBox)it.FindControl("txtQuantitySelect");
                //if (int.Parse(QuantitySelect.Text) > 0)
              //  {
                    saleOrderPromotion.ProductID = ProductID;
                    saleOrderPromotion.SaleOrderRequestID = saleOrderID;
                    saleOrderPromotion.QuantitySelect = int.Parse(QuantitySelect.Text);
                    saleOrderPromotion.PromotionRemainQty = PromotionRemainQty;
                    saleOrderPromotion.Weight = Weight;
                    saleOrderPromotion.PromotionID = PromotionID;
                    saleOrderPromotion.PromotionDetailID = PromotionDetailID;
                    saleOrderPromotion.CreatedBy = Session["UserName"].ToString();
                    saleOrderPromotion.LastUpdatedBy = Session["UserName"].ToString();
                    saleOrderPromotion.CreatedDateTime = DateTime.Now;
                    saleOrderPromotion.LastUpdatedDateTime = DateTime.Now;
                    saleOrderPromotion.Status = 'N';//Moi luu

                    listPro.Add(saleOrderPromotion);
                }
            //}
            db.Insert<SaleOrderRequestPromotion>(listPro);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-InsertPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void DeleteDetail(int? saleOrderID)
    {
        try
        {
            List<SaleOrderRequestDetail> soDetail = (from sd in db.SaleOrderRequestDetails where sd.SaleOrderRequestID == saleOrderID select sd).ToList<SaleOrderRequestDetail>();
            db.Delete<SaleOrderRequestDetail>(soDetail);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-DeleteDetail");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {

        RadWindowManager.Visible = true;
        // RadWindow1.NavigateUrl = "OderRequestSearchItem.aspx?BranchCode=" + cboBranch.SelectedValue + "&HashCode=" + hiddenHashCode.Value;
        RadWindow1.NavigateUrl = "~/Admin/Components/SaleOrder/CustomerPopup.aspx";
        RadWindow1.ID = "Rad1";
        RadWindow1.VisibleOnPageLoad = true;
        RadWindow1.Width = 1100;
        RadWindow1.Height = 400;
        RadWindow1.VisibleStatusbar = false;
        //RadWindowManager.Windows.Clear();
        RadWindowManager.Windows.Add(RadWindow1);
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //RadWindowManager.Windows.Clear();
        if (this.txtCustomerCode.Text.Trim() == "")
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn khách hàng");
            this.txtCustomerCode.Focus();
            return;
        }
        if (this.cboShop.SelectedValue.Trim() == "0" || this.cboShop.SelectedValue.Trim() == "")
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng");
            this.cboShop.Focus();
            return;
        }
        try
        {
            string productID = cboProduct.SelectedValue;
            string productName = cboProduct.SelectedItem.Text;
            string weight = txtWeight.Text;

           
            if (productID != "")
            {
                if (ViewState["CurrentTable"] != null)
                {
                    DataTable dt = (DataTable)ViewState["CurrentTable"];
                    //check ma san pham da chon chua
                    if (dt.Select("ProductID='" + productID + "'").Count() > 0)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm : " + productName + " đã tồn tại. vui lòng chọn sp khác");
                        return;
                    }

                    var pro = (from p in db.Products
                               where p.ID == Convert.ToInt32(productID)
                               && p.Status == 'A'
                               select p).FirstOrDefault();
                    
                    if (pro != null)
                    {
                        var location = db.Shops.FirstOrDefault(s => s.ID == int.Parse(this.cboShop.SelectedValue));

                        var price = (from pr in db.DefinitionPrices
                                     where pr.Status == 'A'
                                     && pr.ProductID == int.Parse(productID)
                                     && pr.LocationID == location.ProvinceID
                                     select pr.Price).FirstOrDefault();
                        if (price == null)
                        {
                            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm : " + productName + " chưa có giá bán. vui lòng tạo giá bán ở màn hình sản phẩm");
                            return;
                        }

                        DataRow drNew = dt.NewRow();
                        drNew["IsPromotion"] = pro.IsPromotion;
                        drNew["IsPoint"] = pro.IsPoint;
                        drNew["ProductID"] = pro.ID;
                        drNew["ProductCode"] = pro.ProductCode;
                        drNew["ProductName"] = productName;
                        drNew["Price"] = String.Format("{0:#,#.##}", price);
                        drNew["Weight"] = weight;
                        double total = Convert.ToDouble(weight) * Convert.ToDouble(price);
                        drNew["Total"] = total.ToString();//String.Format("{0:#,#.##}", total); 
                        dt.Rows.Add(drNew);
                        ViewState["CurrentTable"] = dt;
                    }
                    gvData.DataSource = dt;
                    gvData.DataBind();
                   // int totalWeight = Convert.ToInt32(dt.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"])));
                    int totalWeight = Convert.ToInt32(dt.AsEnumerable().Where(a => a.Field<string>("IsPromotion") == "1").Sum(dr => IntOrNull(dr["Weight"])));
                    sumWeight.InnerText = totalWeight.ToString();
                    int totalWeightSO = Convert.ToInt32(dt.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"])));
                    sumWeightSO.InnerText = totalWeightSO.ToString();
                    CalSum(dt);

                    DataTable dtPro = loadPromotionPromotion(totalWeight, 0);
                    bindingPromotion(dtPro);
                }
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-btnAdd_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void bindingPromotion(DataTable dtPro)
    {
        if (dtPro.Rows.Count > 5)
        {
            gvPromotion.Height = 150;
            gvPromotion.ClientSettings.Scrolling.AllowScroll = true;
        }
        gvPromotion.ClientSettings.Scrolling.UseStaticHeaders = true;
        gvPromotion.DataSource = dtPro;
        gvPromotion.DataBind();

    }
    protected void txtCustomerName_TextChanged(object sender, EventArgs e)
    {
        try
        {
            //RadWindowManager.Windows.Clear();
            string Input = this.txtCustomerName.Text.Trim().ToLower();
            if (Input != "")
            {
                var cus = (from c in db.Customers
                           where c.PhoneNumber.IndexOf(Input) != -1
                           || c.CustomerName.ToLower().IndexOf(Input) != -1
                           || c.CustomerCode.ToLower().IndexOf(Input) != -1
                           select c).FirstOrDefault();
                if (cus != null)
                {
                    this.txtCustomerName.Text = cus.CustomerName;
                    this.txtCustomerCode.Text = cus.CustomerCode;
                    /*
                    String AddressFull = dataItem["Address"].Text + ", " + dataItem["District"].Text + ", " + dataItem["Province"].Text;
                    this.txtReceiptPerson.Text = CustomerName;
                    this.txtReceiptPhoneNumer.Text = CustomerPhone;
                    this.txtReceiptAdress.Text = AddressFull;
                    this.txtCustomerName.Enabled = false;
                     */ 
                }
                else
                {
                    this.txtCustomerName.Text = "";
                    this.txtCustomerCode.Text = "";
                    if (txtCustomerCode.Text == "")
                    {
                       // JavascriptUtil.LoadMessage(UpdatePanel1, false, "Khách hàng này không tồn tại. Vui lòng bấm nút Tìm để tạo khách hàng");
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Khách hàng này không tồn tại. Vui tạo mới khách hàng ơ tab Thông tin khách hàng");
                        RadPageView4.Enabled = true;
                        TabStrip1.SelectedIndex = 1;
                        RadPageView4.Selected = true;
                        return;
                    }
                }
            }
            else
            {
                this.txtCustomerName.Text = "";
                this.txtCustomerCode.Text = "";
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-txtCustomerName_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void RadInput_TextChanged(object sender, EventArgs e)
    {
        try
        {
            //RadWindowManager.Windows.Clear();
            RadNumericTextBox radNumeric = (RadNumericTextBox)sender;

            string QtySelect = radNumeric.Text;
            GridDataItem dataItem = (GridDataItem)radNumeric.NamingContainer;
            string ProductID = dataItem["ProductID"].Text;
            string ProductName = dataItem["ProductName"].Text;
            string Weight = dataItem["Weight"].Text;
            string GvPromotionQuantity = dataItem["PromotionQuantity"].Text;

            int TotalWeightSelect = Convert.ToInt32(QtySelect) * Convert.ToInt32(Weight);
            int totalWeight = Convert.ToInt32(sumWeight.InnerText);
            if (ViewState["dtPromotion"] != null)
            {
                DataTable dtPro = (DataTable)ViewState["dtPromotion"];

                DataRow[] rowArr = dtPro.Select("ProductID='" + ProductID + "'");
                if (Convert.ToInt32(QtySelect) < 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được nhỏ hơn 0");
                    radNumeric.Text = "0";
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = "0";
                    return;
                }
                if (rowArr.Count() > 0)
                {
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = QtySelect;
                }

                int sumWeightSelected = Convert.ToInt32(dtPro.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"]) * IntOrNull(dr["PromotionQuantitySelect"])));
                int totalWeightRemain = totalWeight - sumWeightSelected;
                if (totalWeightRemain < 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được vượt quá số lượng khuyến mãi");
                    radNumeric.Text = "0";
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = "0";
                    return;
                }
                int PromotionQuantity = 0;
                foreach (DataRow r in dtPro.Rows)
                {
                    PromotionQuantity = totalWeightRemain / Convert.ToInt32(r["Weight"]);
                    r["PromotionQuantity"] = PromotionQuantity;
                }
                ViewState["dtPromotion"] = dtPro;
                bindingPromotion(dtPro);
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-RadInput_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private DataTable CreateDataTableSelected()
    {

        DataTable dt = new DataTable();

        if (ViewState["DataTableSelected"] != null)
        {
            dt = (DataTable)ViewState["DataTableSelected"];
        }
        else
        {
            dt.Columns.Add("ProductID");
            dt.Columns.Add("PromotionQuantitySelect");
            dt.Columns.Add("TotalWeight");
            ViewState["DataTableSelected"] = dt;
        }

        return dt;
    }

    private DataTable loadPromotionPromotion(int totalWeight, int totalWeightSelected)
    {

        DataTable dtPromotion = createDataTablPromotion();
        try
        {
            int totalWeightRemain = totalWeight - totalWeightSelected;

            if (totalWeight > 0)
            {

                //Lay danh sach sp KM
                DataTable dtProductPromotion = getListProductPromotion();
                int PromotionQuantity = 0;
                foreach (DataRow detail in dtProductPromotion.Rows)
                {
                    PromotionQuantity = totalWeightRemain / Convert.ToInt32(detail["Weight"]);
                    // if (PromotionQuantity > 0)
                    //{
                    DataRow drNew = dtPromotion.NewRow();
                    drNew["ProductID"] = detail["ProductID"];
                    drNew["ProductCode"] = detail["ProductCode"];
                    drNew["ProductName"] = detail["ProductName"];
                    drNew["PromotionDetailID"] = detail["PromotionDetailID"];
                    drNew["Weight"] = detail["Weight"];
                    drNew["PromotionID"] = detail["PromotionID"];
                    drNew["Image"] = detail["Image"];
                    drNew["PromotionQuantity"] = PromotionQuantity;
                    drNew["PromotionQuantitySelect"] = 0;

                    dtPromotion.Rows.Add(drNew);
                    // }
                }
            }
            ViewState["dtPromotion"] = dtPromotion;
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-loadPromotionPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
            // JavascriptUtil.LoadMessage(UpdatePanel1, false, ex.Message);
        }
        return dtPromotion;
    }

    private DataTable getListProductPromotion()
    {
        DataTable dt = new DataTable();
        try
        {
            string urlImage = Utils.getUrlImage();
            if (CacheUtil.GetCache("ListProductPromotion") == null)
            {
                /*
                DateTime date = DateTime.Now.Date;
                var listPromotion = (from p in db.Promotions
                                     join pd in db.PromotionDetails on p.ID equals pd.PromotionID
                                     join pro in db.Products on pd.ProductID equals pro.ID
                                     where p.Status == 'A' && pd.Status == 'A' && p.PromotionType == "K"
                                     && pro.Status == 'A' && pro.ProductType == "P"
                                     && date >= p.StartDate && date <= p.EndDate
                                     select new
                                     {
                                         ProductID = pd.ProductID,
                                         PromotionID = pd.PromotionID,
                                         PromotionDetailID = pd.ID,
                                         ProductCode = pro.ProductCode,
                                         ProductName = pro.ProductName,
                                         Weight = pd.Weight,
                                         Image = urlImage+pro.ImagePath
                                     }
                                    ).ToList();
                dt = listPromotion.ToDataTable();
                CacheUtil.InsertCache("ListProductPromotion", dt);
                 */
                var listPromotion = db.Promotion_Get(urlImage, int.Parse(this.cboShop.SelectedValue)).ToList();
                dt = listPromotion.ToDataTable();
                CacheUtil.InsertCache("ListProductPromotion", dt);
            }
            else
            {
                dt = (DataTable)CacheUtil.GetCache("ListProductPromotion");
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-getListProductPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return dt;
    }
    private DataTable createDataTablPromotion()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ProductID");
        dt.Columns.Add("ProductCode");
        dt.Columns.Add("ProductName");
        dt.Columns.Add("PromotionDetailID");
        dt.Columns.Add("Weight");
        dt.Columns.Add("PromotionID");
        dt.Columns.Add("Image");
        dt.Columns.Add("PromotionQuantity");
        dt.Columns.Add("PromotionQuantitySelect");
        dt.Columns.Add("Info");
        return dt;
    }
    private void CalSum(DataTable dt)
    {
        try
        {
           
            int totalPoint = Convert.ToInt32(dt.AsEnumerable().Where(a => a.Field<string>("IsPoint") == "1").Sum(dr => IntOrNull(dr["Total"])));
            DivAmountAccumulate.InnerText = totalPoint.ToString();
            //double discount = Convert.ToDouble(CalcDiscount(sum, DateTime.Now.Date));//tinh giam gia
            double discount = Convert.ToDouble(CalcDiscount(totalPoint, DateTime.Now.Date));//tinh giam gia
            
            decimal vat = decimal.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);
            var sum = dt.AsEnumerable().Sum(dr => DecimalOrNull(dr["Total"]));
            CalsumHelp(sum, vat, discount);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-CalSum");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void CalsumHelp(decimal? sum, decimal vat, double discount)
    {
        try
        {
            double Payment = Convert.ToDouble(sum * (vat + 1)) - discount;
            sumTotal.InnerText = "Tổng: " + String.Format("{0:#,#.##}", sum) + " VNĐ";

            if (vat != 0)
            {
                sumTotalTax.Visible = true;
                sumTotalTax.InnerText = "Sau thuế: " + String.Format("{0:#,#.##}", sum * (vat + 1)) + " VNĐ";
            }
            else
            {
                sumTotalTax.Visible = false;
            }
            sumPayment.InnerText = "Thanh toán: " + String.Format("{0:#,#.##}", Payment) + " VNĐ";
            if (discount > 0)
            {
                divDiscount.InnerText = "Giảm giá: " + String.Format("{0:#,#.##}", discount) + " VNĐ";
            }
            else
            {
                divDiscount.InnerText = "Giảm giá: 0 VNĐ";
            }

            DivSumPayment.InnerText = Payment.ToString();//So tien phai thanh toan
            DivAmount.InnerText = sum.ToString();//Tong tien truoc thue
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-CalsumHelp");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private decimal? CalcDiscount(decimal? total, DateTime? date)
    {
        decimal? Discount = 0;
        try
        {
            var cus = (from c in db.Customers
                       where c.CustomerCode == txtCustomerCode.Text.Trim()
                       select c).FirstOrDefault();
            if (cus != null)
            {
                decimal? TotalRemainAmount = DecimalOrNull(cus.RemainAmount) + DecimalOrNull(total);

                //Lay so tien duoc huong KM
                // DateTime date = DateTime.Now.Date;
                var promotion = (from p in db.Promotions
                                 join pd in db.PromotionDetails on p.ID equals pd.PromotionID
                                 join pp in db.PromotionProvinces on p.ID equals pp.PromotionID //honglk 17/06/2015
                                 join s in db.Shops on pp.ProvinceID equals s.ProvinceID//honglk 17/06/2015
                                 where p.Status == 'A' && pd.Status == 'A' && p.PromotionType == "M"
                                 && date >= p.StartDate && date <= p.EndDate
                                 && s.Status == 'A'//honglk 17/06/2015
                                 && s.ID == int.Parse(this.cboShop.SelectedValue)//honglk 17/06/2015
                                 orderby p.LastUpdatedDateTime descending
                                 select new
                                 {
                                     Amount = pd.Amount,
                                     DiscountAmount = pd.DiscountAmount,
                                     PromotionID = pd.PromotionID,
                                     PromotionDetailID = pd.ID,
                                 }
                                    ).First();

                int? number = IntOrNull(TotalRemainAmount < DecimalOrNull(promotion.Amount) ? 0 : (IntOrNull(TotalRemainAmount) / IntOrNull(promotion.Amount)));
                Discount = number * DecimalOrNull(promotion.DiscountAmount);//giam gia
                DivDiscountAmount.InnerText = Discount.ToString();//Giam gia
                DivConvertedAmount.InnerText = (number * promotion.Amount).ToString(); // tong tien da quy doi
                DivDiscountPromotionDetailID.InnerText = promotion.PromotionDetailID.ToString();
                DivDiscountPromotionID.InnerText = promotion.PromotionID.ToString();
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-CalcDiscount");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return Discount;
    }
    protected void grvData_ItemCommand(object sender, GridCommandEventArgs e)
    {

        string commandName = e.CommandName;
        if (commandName == "EditDelItem")
        {

            string ProductID = e.CommandArgument.ToString();
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow[] rows = dt.Select("ProductID=" + ProductID);
            foreach (DataRow r in rows)
            {
                r.Delete();
            }
            ViewState["CurrentTable"] = dt;
            gvData.DataSource = dt;
            gvData.DataBind();

            //tinh lai khuyen mai
           // int totalWeight = Convert.ToInt32(dt.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"])));
            int totalWeight = Convert.ToInt32(dt.AsEnumerable().Where(a => a.Field<string>("IsPromotion") == "1").Sum(dr => IntOrNull(dr["Weight"])));
            sumWeight.InnerText = totalWeight.ToString();
            CalSum(dt);

            DataTable dtPro = loadPromotionPromotion(totalWeight, 0);
            bindingPromotion(dtPro);
        }

    }
    protected void cboIsReceiptBill_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        string isBill = this.cboIsReceiptBill.SelectedValue;
        decimal vat = decimal.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);
        if (isBill.ToString().ToLower() == "n")
        {
            this.cboVAT.Visible = false;

        }
        else
        {
            this.cboVAT.Visible = true;
        }
        CalsumHelp(DecimalOrNull(this.DivAmount.InnerText), vat, double.Parse(this.DivDiscountAmount.InnerText));
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        try
        {
            var saleOrder = db.SaleOrderRequests.FirstOrDefault<SaleOrderRequest>(s => s.SaleOrderRequestCode == txtSaleOrderCode.Text);
            saleOrder.Status = 'E';
            saleOrder.LastUpdatedBy = Session["UserName"].ToString();
            saleOrder.LastUpdatedDateTime = DateTime.Now;
            db.Update<SaleOrderRequest>(saleOrder);
            db.SubmitChanges();
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công!");

           // int ID = int.Parse (ViewState["SaleOrderRequestID"].ToString());
            //loadDataViewFromSOR(ID);
            this.txtSaleOrderStatus.Text = "Hủy bỏ";
            this.btnCancel.Enabled = false;
            this.btnSave.Enabled = false;
            this.RadMultiPag1.Enabled = false;
            this.btnAddProduct.Enabled = false;
           

        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderRequest-btnCancel_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
            return;
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        //RadWindowManager.Windows.Clear();
        Session["Cus"] = null;
        Response.Redirect("~/SaleOrderRequest", true);
      
    }

    private decimal? DecimalOrNull(object val)
    {
        try
        {
            return Convert.ToDecimal(val);
        }
        catch
        {
            return null;
        }
    }
    private int? IntOrNull(object val)
    {
        try
        {
            return Convert.ToInt32(val);
        }
        catch
        {
            return null;
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    /*Khach hang*/
    private void LoadFormForCustomerTab()
    {
        Utils.loadLocation(cboProvince, 0, 1, 0);
        gv.DataSource = new DataTable();
        gv.DataBind();
    }

    protected void gv_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        Loaddata();

    }
    private void Loaddata()
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();

        String CustomerCode = Utils.KillChars(this.txtCustomerCodeNew.Text.Trim());
        String CustomerName = Utils.KillChars(this.txtCustomerNameNew.Text.Trim());
        String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
        int PageNumber = gv.CurrentPageIndex + 1;
        int PageSize = gv.PageSize;

        DateTime FromDate = new DateTime(2014, 06, 01);
        DateTime ToDate = new DateTime(2099, 12, 31);
        var q = db.Customer_Search(CustomerCode, CustomerName, CustomerPhone, "", 0, 0, FromDate, ToDate, PageSize, PageNumber).ToList();
        if (q.Count > 0)
        {
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.VirtualItemCount = q[0].TotalRows.Value;
            gv.DataSource = q;
            if (q.Count > 5)
            {
                //gv.Height = 120;
                gv.ClientSettings.Scrolling.AllowScroll = true;
              
                gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            }
        }
    }
    protected void btnCusSave_Click(object sender, EventArgs e)
    {
        try
        {
            DBDataContext dbread = LINQUtil.GetDBWriteOnly();
            Customer customer = new Customer();

            // String CustomerCode = Utils.KillChars(this.txtCustomerCode.Text.Trim());
            String CustomerName = Utils.KillChars(this.txtCustomerNameNew.Text.Trim());
            String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
           // String Email = Utils.KillChars(this.txtEmail.Text.Trim());
            String Address = Utils.KillChars(this.txtAddress.Text.Trim());
            int DistrictID = Convert.ToInt32(this.cboDistrict.SelectedValue == "" ? "0" : this.cboDistrict.SelectedValue);
            int ProvinceID = Convert.ToInt32(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);

            //Check khong cho phep trung do dien thoai
            var check = (from cus in dbread.Customers
                         where cus.PhoneNumber == CustomerPhone
                         select cus).FirstOrDefault();
            if (check != null)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số điện thoại: " + CustomerPhone + " đã tồn tại. vui lòng chọn số khác");
                return;
            }

            //Lay ma sau cung
            int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
            var customerCodeMax = dbread.Customers.Max(d => d.OrderNumber);
            int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
            String LastCode = ("000000" + MaxOrderNumber).ToString();
            String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
            //End

            customer.CustomerCode = CustomerCode;
            customer.CustomerName = CustomerName;
            customer.PhoneNumber = CustomerPhone;
           // customer.Email = Email;
            customer.Address = Address;
            customer.DistrictID = DistrictID;
            customer.ProvinceID = ProvinceID;
            customer.AccumulateAmount = 0;
            customer.ConvertedAmount = 0;
            customer.RemainAmount = 0;
            customer.CreatedBy = Session["UserName"].ToString();
            customer.CreatedDateTime = DateTime.Now;
            customer.LastUpdatedBy = Session["UserName"].ToString();
            customer.LastUpdatedDateTime = DateTime.Now;
            customer.Status = 'A';
            customer.OrderNumber = MaxOrderNumber;
            dbread.Insert<Customer>(customer);
            dbread.SubmitChanges();

            String DistrictName = cboDistrict.SelectedItem.Text;
            String ProvinceName = cboProvince.SelectedItem.Text;
            string AddressFull = Address + ", " + DistrictName + ", " + ProvinceName;
            this.txtCustomerCodeNew.Text = CustomerCode;
            //Session["Cus"] = CustomerCode + "@" + CustomerName;
            this.txtCustomerCode.Text = CustomerCode;
            this.txtCustomerName.Text = CustomerName;

            this.txtReceiptPerson.Text = CustomerName;
            this.txtReceiptPhoneNumer.Text = CustomerPhone;
            this.txtReceiptAdress.Text = AddressFull;

            TabStrip1.SelectedIndex = 0;
            RadPageView1.Selected = true;
            this.txtCustomerName.Enabled = false;
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu thành công!");
           
          //  ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "','" + CustomerPhone + "','" + AddressFull + "');", true);
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("----------------------------");
            ControlUtil.LogError("SaleOrderRequest-btnCusSave_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("----------------------------");
        }
    }
    protected void btnCusSearch_Click(object sender, EventArgs e)
    {
        Loaddata();
        gv.DataBind();
    }
    protected void lnkCustomerCode_Click(object sender, EventArgs e)
    {
        LinkButton LNKCustomer = (LinkButton)sender;
        GridDataItem dataItem = (GridDataItem)LNKCustomer.NamingContainer;
        String CustomerName = dataItem["CustomerName"].Text;
        String CustomerCode = LNKCustomer.Text;
        String CustomerPhone = dataItem["PhoneNumber"].Text;
        

        this.txtCustomerCode.Text = CustomerCode;
        this.txtCustomerName.Text = CustomerName;
        String AddressFull = dataItem["Address"].Text + ", " + dataItem["District"].Text + ", " + dataItem["Province"].Text;

        this.txtReceiptPerson.Text = CustomerName;
        this.txtReceiptPhoneNumer.Text = CustomerPhone;
        this.txtReceiptAdress.Text = AddressFull;

        TabStrip1.SelectedIndex = 0;
        RadPageView1.Selected = true;
        this.txtCustomerName.Enabled = false;
       // Session["Cus"] = CustomerCode + "@" + CustomerName;
        // ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "');", true);
        //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "','" + CustomerPhone + "','" + AddressFull + "');", true);
    }
    protected void cboProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        string provinceID = cboProvince.SelectedValue;
        Utils.loadLocation(cboDistrict, int.Parse(provinceID), 0, 0);
    }
}